package com.je.gateway.filter;

import com.google.common.base.Strings;
import com.je.gateway.router.dispatcher.GatewayAbstractRestDispatcher;
import org.apache.servicecomb.core.Invocation;
import org.apache.servicecomb.loadbalance.ServerListFilterExt;
import org.apache.servicecomb.loadbalance.ServiceCombServer;

import java.util.List;
import java.util.stream.Collectors;

public class GetSpecifiedInstanceServerListFilter implements ServerListFilterExt {

    @Override
    public List<ServiceCombServer> getFilteredListOfServers(List<ServiceCombServer> servers, Invocation invocation) {
        // 自定义过滤规则
        return servers.stream()
                .filter(server -> specifyInstanceId(server, invocation))
                .collect(Collectors.toList());
    }

    private Boolean specifyInstanceId(ServiceCombServer serviceCombServer, Invocation invocation) {
        String instanceId = invocation.getContext().get(GatewayAbstractRestDispatcher.SERVICE_INSTANCE);
        if (Strings.isNullOrEmpty(instanceId)) {
            return true;
        }
        if (serviceCombServer.getInstance().getInstanceId().equals(instanceId)) {
            return true;
        }
        return false;
    }

    @Override
    public boolean enabled() {
        return true;
    }

}

